﻿using cap_demo.Domain.Events;
using cap_demo.Repository;
using cap_demo.Repository.Infrastrcture;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cap_demo.Extensions
{
    public static class ServiceCollectionExtensions
    {

        public static IServiceCollection AddMediatRService(this IServiceCollection services)
        {
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(OrderingContextTransactionBehavior<,>));// TODO 待跟进这个运行声明周期
            return services.AddMediatR(typeof(Program).Assembly);
        }


        public static IServiceCollection AddMySqlDomainContext(this IServiceCollection services, string connectionString)
        {
            return services.AddDomainContext(builder =>
            {
                builder.UseMySql(connectionString, ServerVersion.Parse("mysql-5.7.17"));
            });
        }

        public static IServiceCollection AddDomainContext(this IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction)
        {
            return services.AddDbContext<OrderingContext>(optionsAction);
        }

        public static IServiceCollection AddRepositories(this IServiceCollection services)
        {
            services.AddScoped<IOrderRepository, OrderRepository>();
            return services;
        }

        /// <summary>
        /// CAP组件配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddTransient<ISubscriberService, SubscriberService>();
            services.AddCap(options =>
            {
                // bug link: https://github.com/dotnetcore/CAP/issues/539  fix use sql configuration
                //options.UseEntityFramework<OrderingContext>();
                options.UseMySql(configuration.GetValue<string>("Mysql"));
                options.UseRabbitMQ(options =>
                {
                    configuration.GetSection("RabbitMQ").Bind(options);
                });
                options.UseDashboard();
            });

            return services;
        }
    }
}
